//
//  BoutiqueViewController.m
//  半糖
//
//  Created by RenShuang on 15/9/15.
//  Copyright (c) 2015年 shuang. All rights reserved.
//

#import "BoutiqueViewController.h"
#import "BaseHeader.h"

@interface BoutiqueViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,retain)UIView *upView;
@property(nonatomic,retain)UIScrollView *myScrollView;
@property(nonatomic,retain)UITableView *myTableView;
@property(nonatomic,retain)UICollectionView *myCollectionView;
@property(nonatomic,retain)NSMutableArray *tableArr;
@property(nonatomic,retain)NSMutableArray *collectionArr;
@property(nonatomic,assign)NSInteger collectFooter;
@property(nonatomic,assign)NSInteger tableFooter;
@property(nonatomic,retain)UISegmentedControl *segment;
@end

@implementation BoutiqueViewController

- (void)dealloc
{
    [_upView release];
    [_myCollectionView release];
    [_myScrollView release];
    [_myTableView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.myCollectionView.backgroundColor = [NightHandle shareHandle].searchBackgroundColor;
    [self.myTableView reloadData];
    [self.myCollectionView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableArr = [[NSMutableArray alloc] init];
    self.collectionArr = [[NSMutableArray alloc] init];
    self.collectFooter = 0;
    self.tableFooter = 0;
    
    [GiFHUD setGifWithImageName:@"giff.gif"];
    
    _upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    _upView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_upView];
    [_upView release];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(20, 30, 30, 25);
    [backButton setBackgroundImage:[UIImage imageNamed:@"fanhui.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [_upView addSubview:backButton];
    
    NSArray *segArr = @[@"单品",@"专题"];
    self.segment = [[UISegmentedControl alloc] initWithItems:segArr];
    self.segment.frame = CGRectMake(SCREEN_WIDTH/2-75, 28, 150, 30);
    [self.segment setTintColor:[UIColor whiteColor]];
    [self.segment addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
    self.segment.selectedSegmentIndex = 0;
    [_upView addSubview:self.segment];
    [self.segment release];
    
    self.myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.myScrollView.delegate = self;
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH*2, 0);
    [self.view addSubview:self.myScrollView];
    [_myScrollView release];
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    self.myTableView.delegate =self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myScrollView addSubview:self.myTableView];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-30)/2, SCREEN_WIDTH/2);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) collectionViewLayout:flowLayout];
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    [self.myScrollView addSubview:self.myCollectionView];
    
    [self.myCollectionView registerClass:[SingleCollectionViewCell class] forCellWithReuseIdentifier:@"SingleCollectionViewCell"];
    
    [self collectionData];
    [self tableData];
    
    [self.myCollectionView addLegendHeaderWithRefreshingBlock:^{
        [self.myCollectionView.header endRefreshing];
    }];
    [self.myCollectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(collectionData)];
    [self.myTableView addLegendHeaderWithRefreshingBlock:^{
        [self.myTableView.header endRefreshing];
    }];
    [self.myTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(tableData)];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)collectionData
{
    [GiFHUD show];
    NSString *collectionStr = [[NSString stringWithFormat:@"http://open3.bantangapp.com/base/search/list?app_installtime=1440915950.090587&app_versions=4.1.1&category=12&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&oauth_token=6de3bace25123737e17db3e839477eb1&os_versions=8.2&page=%ld&pagesize=20&screensize=640&track_device_info=iPhone&track_deviceid=B4391E1B-981F-4473-A960-431F69E76E8C&track_user_id=1260331&type_id=2&v=6",self.url_Str,(long)self.collectFooter]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.collectFooter++;
    [AFNBlock getDataWithString:collectionStr block:^(id block) {
        for (NSDictionary *dic in [block objectForKey:@"data"]) {
            SingleModel *model = [SingleModel modelWithDictionary:dic];
            model.cid = [dic objectForKey:@"id"];
            [self.collectionArr addObject:model];
        }
        if (self.collectionArr.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有您要搜的东西" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }

        [self.myCollectionView.footer endRefreshing];
        [self.myCollectionView reloadData];
        [GiFHUD dismiss];
    }];
}

- (void)tableData
{
    NSString *tableStr = [[NSString stringWithFormat:@"http://open3.bantangapp.com/base/search/list?app_installtime=1440915950.090587&app_versions=4.1.1&category=12&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&oauth_token=6de3bace25123737e17db3e839477eb1&os_versions=8.2&page=%ld&pagesize=20&screensize=640&track_device_info=iPhone&track_deviceid=B4391E1B-981F-4473-A960-431F69E76E8C&track_user_id=1260331&type_id=1&v=6",self.url_Str,(long)self.tableFooter] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.tableFooter++;
    [AFNBlock getDataWithString:tableStr block:^(id block) {
        for (NSDictionary *dic in [block objectForKey:@"data"]) {
            SingleModel *model = [SingleModel modelWithDictionary:dic];
            model.cid = [dic objectForKey:@"id"];
            [self.tableArr addObject:model];
        }
//        if (self.tableArr.count == 0) {
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有您要搜的东西" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//            [alert show];
//            [alert release];
//        }
        [self.myTableView.footer endRefreshing];
        [self.myTableView reloadData];
    }];
    
}

- (void)click:(UISegmentedControl *)seg
{
    self.myScrollView.contentOffset = CGPointMake(SCREEN_WIDTH*seg.selectedSegmentIndex, 0);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.segment.selectedSegmentIndex = self.myScrollView.contentOffset.x/(SCREEN_WIDTH/2+1);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectionArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SingleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SingleCollectionViewCell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [NightHandle shareHandle].viewColor;
    cell.titleLabel.textColor = [NightHandle shareHandle].wordColor;
    SingleModel *model = [self.collectionArr objectAtIndex:indexPath.row];
    [cell getModel:model key:self.url_Str];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController *detail = [[WebViewController alloc] init];
    SingleModel *model = [self.collectionArr objectAtIndex:indexPath.row];
    detail.urlStr = model.cid;
    [self.navigationController pushViewController:detail animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SCREEN_HEIGHT*1/3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"cell";
    SingleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[SingleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }
    cell.whiteView.backgroundColor = [NightHandle shareHandle].viewColor;
    cell.titleLabel.textColor = [NightHandle shareHandle].wordColor;
    cell.contentView.backgroundColor = [NightHandle shareHandle].searchBackgroundColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SingleModel *model = [self.tableArr objectAtIndex:indexPath.row];
    [cell getCell:model searchStr:self.url_Str];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableDetailViewController *detail = [[TableDetailViewController alloc] init];
    SingleModel *model = [self.tableArr objectAtIndex:indexPath.row];
    detail.str = model.cid;
    detail.titleStr = model.title;
    detail.picStr = model.pic;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [GiFHUD dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
